package com.ruoyi.business.service.impl;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.business.domain.TiffSeg;
import com.ruoyi.business.mapper.TiffSegMapper;
import com.ruoyi.business.service.ITiffSegService;
import com.ruoyi.business.utils.OSSUtil;
import com.ruoyi.business.utils.SecurePasswordGenerator;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@Service
public class TiffSegService implements ITiffSegService {

    private static Logger logger = LoggerFactory.getLogger(TiffSegService.class);

    @Autowired
    private TiffSegMapper tiffSegMapper;

    @Autowired
    private TiffProcessService tiffProcessService;

    @Autowired
    private TiffUploadService tiffUploadService;

    @Value("${oss.tiff_bucket}")
    private String tiff_bucket;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.region}")
    private String region;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.defaultRegion}")
    private String defaultRegion;

    @Value("${oss.expireTime}")
    private int expireTime;

    @Value("${share.url}")
    private String shareUrl;

    @Value("${ruoyi.profile}")
    private String profile;

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<TiffSeg> selectTiffList(TiffSeg tiffSeg) {
        List<TiffSeg> list = tiffSegMapper.selectTiffList(tiffSeg);
        return list;
    }

    @Override
    public TiffSeg selectTiffById(Long id) {
        return tiffSegMapper.selectTiffById(id);
    }

    @Override
    public boolean insertTiff(TiffSeg tiffSeg) {
        boolean result = tiffSegMapper.insertTiff(tiffSeg) > 0;
        tiffUploadService.processImage(tiffSeg.getFileName(), tiffSeg.getId(), tiffSeg.getOriginalFileName());
        return result;
    }

    @Override
    public boolean updateTiff(TiffSeg tiffSeg) {
        return tiffSegMapper.updateTiff(tiffSeg) > 0;
    }

    @Override
    public boolean updateStatus(String status, Long id) {
        int i = tiffSegMapper.updateStatus(status, id);
        return i > 0;
    }

    @Override
    public boolean deleteTiffById(Long id) {
        return tiffSegMapper.deleteTiffById(id) > 0;
    }

    @Override
    public boolean deleteTiffByIds(List<Long> array) {
        return tiffSegMapper.deleteTiffByIds(array) > 0;
    }

    @Override
    public AjaxResult uploadFile(MultipartFile file) {
        AjaxResult ajax = AjaxResult.success();
        try {

            // 将文件保存到本地
            String filePath = profile + "/upload";;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            fileName = fileName.replace(Constants.RESOURCE_PREFIX, profile);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFileName", file.getOriginalFilename());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }
    @Override
    public AjaxResult downloadTiff(Long id) {
        AjaxResult ajax = AjaxResult.success();
        try {
            TiffSeg tiffSeg = tiffSegMapper.selectTiffById(id);
            String objectName = tiffSeg.getObjectName();
            OSSUtil ossUtil = new OSSUtil(endpoint, region, accessKeyId, accessKeySecret);
            String downloadUrl = ossUtil.getFileUrl(tiff_bucket, objectName, expireTime);
            ajax.put("downloadUrl", downloadUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }

    @Override
    public AjaxResult createShareUrl(Long id, Long userId) {
        AjaxResult ajax = AjaxResult.success();
        try {
            TiffSeg tiffSeg = tiffSegMapper.selectTiffById(id);
            if (tiffSeg == null) {
                return AjaxResult.error("数据已消失，请刷新页面重新操作！");
            }
            String sharePassword = SecurePasswordGenerator.generateSecurePassword() + "_" + id;
            int i = tiffSegMapper.updateSharePassword(sharePassword, userId, id);
            ajax.put("sharePassword", sharePassword);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }

    @Override
    public AjaxResult previewTiff(Long id) {
        AjaxResult ajax = AjaxResult.success();
        try {
            TiffSeg tiffSeg = tiffSegMapper.selectTiffById(id);
            if (tiffSeg == null) {
                return AjaxResult.error("数据已消失，请刷新页面重新操作！");
            }

            String dziObjectName = tiffSeg.getDziObjectName();
            String encodeUrl = URLEncoder.encode(defaultRegion + dziObjectName, "UTF-8");
            ajax.put("previewUrl", shareUrl + "?previewUrl=" + encodeUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }

    @Override
    public AjaxResult validPassword(String password) {
        AjaxResult ajax = AjaxResult.success();
        try {
            String[] arr = password.split("_");
            long id = Long.parseLong(arr[1]);

            // 以"a1d3m4i5n6"结尾的密码，不需要考虑状态是否可用
            int admin = 0;
            if (password.startsWith("A1d3M4i5N6")) {
                admin = 1;
            }
            TiffSeg tiffSeg = tiffSegMapper.selectTiffByIdWithStatus(id, admin);
            if (tiffSeg == null) {
                return AjaxResult.error("数据已消失，请刷新页面重新操作！");
            }
            String sharePassword = tiffSeg.getSharePassword();
            String dziObjectName = tiffSeg.getDziObjectName();
            String previewUrl = defaultRegion + dziObjectName;
            // 以"a1d3m4i5n6"结尾的密码，直接返回预览url
            if (password.startsWith("A1d3M4i5N6")) {
                ajax.put("previewUrl", previewUrl);
                return ajax;
            }

            if (!password.equals(sharePassword)) {
                return AjaxResult.error("密码错误，请重新输入！");
            }
            ajax.put("previewUrl", previewUrl);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return ajax;
    }

    @Override
    public AjaxResult beginSeg(Long id) {
        try {
            TiffSeg tiffSeg = tiffSegMapper.selectTiffById(id);
            // 修改Tiff文件是否已分割完成的状态
            tiffSegMapper.updateIsSeg(id, 2);
            tiffProcessService.processImage(tiffSeg.getFileName(), tiffSeg.getId());
            return AjaxResult.success("tiff正在进行分割处理，请刷新页面查看分割结果");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error("Tiff文件分割失败！");
        }
    }
}
